<template>
	<view class="">
		<NavBar title="积分商城" :isShowLeftBtn="false">
		</NavBar>
	</view>
	<view class="search_box " style="padding-top: 20rpx;">
		<view class="search_input" :style="searchVal?{width:'710rpx'}:{paddingLeft:'46rpx',width:'666rpx'}">
			<view class="">
				<view class="search_icon" v-if="!searchVal">
					<up-icon name="search" color="#7E7D7D" size="18"></up-icon>
				</view>
				<view class="" style="">
					<up-input placeholder="请输入关键字" border="none" v-model="searchVal" inputAlign="center"
						fontSize="24rpx" @change="onSearchChage"></up-input>
				</view>
			</view>
		</view>
	</view>
	<view class="" style="height: 106rpx;background: #F7F8FC;">
	</view>
	<view class="content" :style="{minHeight:contentHeight}">
		<view class="main">
			<view class="m_b_38 flex_both">
				<view class="">
					<text class="f_28_0_b" style="color: #F93E19;">
						我的积分：<text style="font-weight: bold;">{{pointsInfo}}</text>
					</text>
				</view>
				<view class="flex">
					<view class=" flex" @click="showCityPicker">
						<view class="m_r_8" style="max-width: 400rpx;">
							<text class="f_26_0 u-line-1">
								{{curAddress}}
							</text>
						</view>
						<view class="">
							<up-icon name="arrow-down-fill" size="14"></up-icon>
						</view>
					</view>

				</view>
			</view>
			<view class="float_box">
				<view class=" float_item m_b_10" @click="toGetLog">
					<text class="f_24_0" style="color: #ffffff;text-align: center;">
						积分记录
					</text>
				</view>
				<view class="float_item" @click="toLog">
					<text class="f_24_0" style="color: #ffffff;text-align: center;">
						兑换记录
					</text>
				</view>
			</view>
			<scroll-view scroll-y="true" :style="{height: contentHeight}" :refresher-threshold="100"
				@scrolltolower="scrolltolowerFun" refresher-enabled="true" refresher-default-style="none">
				<view class="main_list flex_both">
					<view class="main_item m_b_28" v-for="(item,index) in shopList" :key="index">
						<view class="">
							<up-image :show-loading="true" :src="item.image" width="342rpx" height="342rpx"></up-image>
						</view>
						<view class="main_item_info">
							<view class="m_b_22">
								<text class="f_24_0">
									{{item.name}}
								</text>
							</view>
							<view class="flex_both">
								<view class="f_24_0" style="color: #F93E19;">
									积分：{{item.points}}
								</view>
								<view class="flex"
									style="width: 77rpx;height: 35rpx;border: 1px solid #F93E19;border-radius: 17rpx;justify-content: center;"
									@click="showModal(index)">
									<view class="f_22_0 m_b_4" style="color: #F93E19;">
										<text class="">
											兑换
										</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="empty_box" v-if="!loadShow &&shopList.length ==  0">
					<view class="">
						<up-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
						</up-empty>
					</view>
				</view>
				<view class="loading_box m_t_32 " style="padding-bottom: 32rpx;" v-if="loadShow">
					{{ loadMessage }}
				</view>
			</scroll-view>
		</view>
	</view>
	<up-modal :show="modalShow" title="提示" content='确定要兑换该商品吗?' :showCancelButton="true" confirmColor="#FA5A28"
		@confirm="onModalOk" @cancel="onModalCancel"></up-modal>
	<up-modal :show="successShow" content='商品兑换已提交管理员审核，24小时内到账！' confirmColor="#FA5A28"
		@confirm="onSuccessConfirm"></up-modal>
	<up-picker ref="uCityPickerRef" :show="cityPickerShow" :columns="cityArr" keyName="name"
		@change="cityPickerChangeHandler" @cancel="cityPickerShow = false" @confirm="cityPickerConfirm"
		:defaultIndex="defaultIndex" confirmColor="#F76D11"></up-picker>
	<Tabbar :activeTab="1"></Tabbar>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import { onLoad, onShow, onReady } from "@dcloudio/uni-app";
	import NavBar from "@/components/navbar.vue"
	import Tabbar from "@/components/user/tabbar.vue"
	import QQMapWX from '@/common/qqmap-wx-jssdk.js'
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const statusBarHeight = ref(88)
	const token = ref()
	onLoad(() => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight + 44) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value + 80 + 108 + 22}rpx - env(safe-area-inset-bottom) - 100rpx)`
			}
		});
		token.value = uni.getStorageSync('token');

	})
	onShow(() => {
		if (!token.value) {
			proxy.$gloab.gotoPage('/pages/login/index')
			return
		}
		// loadMessage.value = "加载中"
		// page.value = 1
		// shopList.value = []
		// getMallList()
	})
	// 个人信息
	const pointsInfo = ref()
	const getMyPoints = async () => {
		let res = await proxy.$http('points.getMyPoints', { ...positionInfo.value })
		let data = res.data
		pointsInfo.value = data
	}
	// 商品列表
	const page = ref(1)
	const loadShow = ref(false)
	const loadMessage = ref('加载中')
	const scrolltolowerFun = () => {
		if (loadShow.value) return
		page.value = ++page.value;
		loadShow.value = true;
		setTimeout(() => {
			getMallList()
		}, 1000)
	}
	// 评价列表 取前两条
	const shopList = ref([])
	const getMallList = async () => {
		if (loadMessage.value == '没有更多了') {
			loadShow.value = true;
			setTimeout(() => {
				loadShow.value = false;
			}, 200)
			return
		}
		let res = await proxy.$http('points.getMallList', { page: page.value, search: searchVal.value, ...positionInfo.value })
		let data = res.data.data
		if (res.code == 1) {
			if (data.length == 0) {
				loadMessage.value = "没有更多了"
			} else {
				shopList.value.push(...data)
			}
		} else {
			loadMessage.value = "加载出错"
		}
		setTimeout(() => {
			loadShow.value = false;
		}, 200)
	}
	// 积分兑换
	const modalShow = ref(false)
	const activeIdx = ref()
	const showModal = (e) => {
		activeIdx.value = e
		modalShow.value = true
	}
	const onModalOk = () => {
		modalShow.value = false
		exchangeMall()
	}
	const onModalCancel = () => {
		modalShow.value = false
	}
	const successShow = ref(false)

	const exchangeMall = async () => {
		let res = await proxy.$http('points.exchangeMall', { mall_id: shopList.value[activeIdx.value].mall_id, ...positionInfo.value })
		if (res.code == 1) {
			successShow.value = true

		}
	}
	const onSuccessConfirm = () => {
		successShow.value = false
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/pointsShop/pointsLog'
			}, 800)
		})
	}
	const searchVal = ref('')
	const timer = ref(null)
	const onSearchChage = (e) => {
		searchVal.value = e
		loadMessage.value = "加载中"
		page.value = 1
		shopList.value = []
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			getMallList()
		}, 200)
	}
	const initData = () => {
		loadMessage.value = "加载中"
		page.value = 1
		shopList.value = []
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			getMallList()
		}, 200)
	}
	const isSel = ref(false)
	const toLog = () => {
		uni.navigateTo({
			url: '/pages/pointsShop/pointsLog'
		})
	}
	const toGetLog = () => {
		uni.navigateTo({
			url: '/pages/pointsShop/getLog'
		})
	}
	// 区县相关
	const qqmapsdk = ref(null)
	onReady(() => {
		qqmapsdk.value = new QQMapWX({
			key: proxy.$config.txMapKey
		});
		getLoaction()
	})
	const longitude = ref()
	const latitude = ref()

	const getLoaction = () => {
		uni.getLocation({
			type: 'gcj02', // 返回可以用于uni.openLocation的经纬度
			success: function (res) {
				longitude.value = res.longitude
				latitude.value = res.latitude
				qqmapsdk.value.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					},
					success: (res2) => {
						console.log(res2);
						// let data = res2.result.address_component
						// curAddress.value = res2.result.formatted_addresses.standard_address
						// console.log(data);
						// getDistrictByCityId(res2)
						// 获取区id
						getNowAreaByName(res2.result)
					},
					fail: (e) => {
						console.log(e, 'eee')
					}
				})

				// 获取附近房屋
			},
			fail: function (e) {
				// uni.setStorageSync('position_info', { code: 2, longitude: 0, latitude: 0 })
				console.log('获取位置信息失败：' + JSON.stringify(e));
			}
		});
	}
	const getNowAreaByName = async (e) => {
		let res = await proxy.$http("common.getNowAreaByName", { area_name: e.address_component.district, city_name: e.address_component.city })
		let data = res.data
		curAddress.value = data.province.name + '-' + data.cityInfo.name + '-' + data.areaInfo.name
		initCity(res.data)
	}
	// 区县相关
	const cityPickerShow = ref(false)
	const uCityPickerRef = ref(null)
	const rawCityData = ref([])
	const cityArr = ref([])
	const curAddress = ref('')
	const defaultIndex = ref([0, 3, 2])
	const positionInfo = ref({
		province_name: '',
		city_name: '',
		area_name: ''

	})
	const initCity = async (e) => {
		try {
			let res = await proxy.$http('common.getAreaAll')
			if (res.code === 1) {
				defaultIndex.value = []
				rawCityData.value = res.data
				positionInfo.value.province_name = e.province.name
				positionInfo.value.city_name = e.cityInfo.name
				positionInfo.value.area_name = e.areaInfo.name
				const provinceList = rawCityData.value.map(item => {
					return { name: item.name, id: item.id }
				})
				let provinceIndex = 0
				provinceList.forEach((v, index) => {
					if (v.id == e.province.id) {
						provinceIndex = index
						defaultIndex.value.push(index)
					}
				})
				const cityList = rawCityData.value[provinceIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				let cityIndex = 0
				cityList.forEach((v, index) => {
					if (v.id == e.cityInfo.id) {
						defaultIndex.value.push(index)
						cityIndex = index
					}
				})
				const counties = rawCityData.value[provinceIndex].children[cityIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				counties.forEach((v, index) => {
					if (v.id == e.areaInfo.id) {
						defaultIndex.value.push(index)
					}
				})
				console.log(defaultIndex.value);
				cityArr.value.push(provinceList, cityList, counties)
				getMyPoints()
				initData()
			} else {
				throw new Error(res.msg)
			}
		} catch (e) {
			uni.showToast({
				icon: 'none',
				title: e.message
			})
		}
	}
	const showCityPicker = () => {
		cityPickerShow.value = true
	}
	const cityPickerChangeHandler = (e) => {
		const { columnIndex, indexs } = e
		if (columnIndex === 0) {
			uCityPickerRef.value.setColumnValues(1, rawCityData.value[indexs[0]].children);
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[0].children);
		}
		if (columnIndex === 1) {
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[indexs[1]].children);
		}
	}
	const cityPickerConfirm = (e) => {
		const arr = []
		arr.push(e.value[0].name)
		arr.push(e.value[1].name)
		arr.push(e.value[2].name)
		curAddress.value = arr.join('-')
		positionInfo.value.province_name = e.value[0].name
		positionInfo.value.city_name = e.value[1].name
		positionInfo.value.area_name = e.value[2].name
		cityPickerShow.value = false
		initData()
		getMyPoints()
	}
</script>
<style lang="scss" scoped>
	.content {
		background: #F7F8FC;
		padding: 20rpx 20rpx;
		// padding-bottom: 64rpx;

		.main {
			.float_box {
				position: fixed;
				right: 20rpx;
				bottom: calc(env(safe-area-inset-bottom) + 260rpx);
				z-index: 9;

				.float_item {
					width: 60rpx;
					height: 60rpx;
					padding: 16rpx;
					background: #FD6C25;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 50%;
				}
			}

			.main_list {
				flex-wrap: wrap;

				.main_item {
					width: 341rpx;
					background: #FFFFFF;
					box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
					border-radius: 10rpx;
					overflow: hidden;

					.main_item_info {
						padding: 22rpx 20rpx;
					}
				}
			}
		}

	}

	.search_box {
		width: 750rpx;
		height: 66rpx;
		background: #F7F8FC;
		position: fixed;

		.search_input {
			padding: 11rpx 0;
			margin-left: 20rpx;
			background: #FFFFFF;
			box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
			border-radius: 34rpx;
			position: relative;


			.search_icon {
				position: absolute;
				left: 260rpx;
				top: 16rpx;
			}
		}
	}
</style>